package ink.metoo.gude.module.file.service.impl

import ink.metoo.gude.properties.CloudflareProperties
import ink.metoo.gude.module.file.service.FileService
import org.springframework.web.multipart.MultipartFile
import software.amazon.awssdk.core.sync.RequestBody
import software.amazon.awssdk.services.s3.S3Client
import software.amazon.awssdk.services.s3.model.PutObjectRequest


class R2FileServiceImpl(
    private val cloudflareProperties: CloudflareProperties,
    private val s3Client: S3Client,
) : FileService {

    private val bucket
        get() = cloudflareProperties.r2.bucket

    override fun upload(key: String, file: MultipartFile): String {
        val putObjectRequest = PutObjectRequest.builder()
            .bucket(bucket)
            .key(key)
            .contentType(file.contentType)
            .contentLength(file.size)
            .build()

        s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.inputStream, file.size))
        return cloudflareProperties.r2.domain + "/" + key
    }

}